package org.hepeng.commons.spring.web.client;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Objects;

/**
 * 将 http request 中的请求头拷贝携带到本次 {@link org.springframework.web.client.RestTemplate} 发起的 http 请求中
 * @author he peng
 */
public class HeaderCopyingHttpRequestInterceptor implements ClientHttpRequestInterceptor {

    private static final Logger LOG = LoggerFactory.getLogger(HeaderCopyingHttpRequestInterceptor.class);

    @Override
    public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes, ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {
        ServletRequestAttributes requestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpHeaders headers = httpRequest.getHeaders();
        if (Objects.nonNull(requestAttributes) && Objects.nonNull(headers)) {
            HttpServletRequest httpServletRequest = requestAttributes.getRequest();
            Enumeration<String> headerNames = httpServletRequest.getHeaderNames();
            while (headerNames.hasMoreElements()) {
                String headerName = headerNames.nextElement();
                String headerValue = httpServletRequest.getHeader(headerName);
                headers.add(headerName , headerValue);

                LOG.debug("http request header copying , name {} , value {} " , headerName , headerValue);
            }
        } else {
            LOG.warn("Unable to copy http request header , cause ServletRequestAttributes is {} , HttpHeaders is {} " ,
                    requestAttributes , headers);
        }
        return clientHttpRequestExecution.execute(httpRequest , bytes);
    }
}
